import React, { useState } from 'react';
import styled from 'styled-components';
import { Tabs, Button, message, Space, Typography } from 'antd';
import { CopyOutlined, DownloadOutlined, CheckOutlined, EyeOutlined } from '@ant-design/icons';

interface Cell {
  rowSpan: number;
  colSpan: number;
  content: string;
}

interface CodePreviewProps {
  tableData: {
    rows: number;
    cols: number;
    cells: Cell[][];
  };
}

const PreviewContainer = styled.div`
  width: 1000px;
  padding: 16px;
  background-color: #f0f2f5;
  border-left: 1px solid #d9d9d9;
  display: flex;
  flex-direction: column;
  height: 100%;
  box-shadow: -2px 0 8px rgba(0,0,0,0.05);
`;

const CodeBlock = styled.pre`
  background-color: #282c34;
  color: #abb2bf;
  padding: 16px;
  border-radius: 4px;
  overflow: auto;
  font-family: 'Consolas', 'Monaco', 'Andale Mono', monospace;
  font-size: 14px;
  line-height: 1.5;
  max-height: calc(100vh - 260px);
  flex: 1;
  margin: 16px 0;
  border: 1px solid #1a1a1a;
  box-shadow: 0 2px 8px rgba(0,0,0,0.2);
  text-align: left;
`;

const ButtonContainer = styled.div`
  margin-top: 16px;
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
  gap: 8px;
`;

const StyledButton = styled(Button)`
  flex: 1;
  min-width: 120px;
`;

const { TabPane } = Tabs;
const { Title } = Typography;

const CodePreview: React.FC<CodePreviewProps> = ({ tableData }) => {
  const [activeTab, setActiveTab] = useState<string>('html');
  const [copySuccess, setCopySuccess] = useState(false);

  // 生成完整的HTML文档
  const generateHTMLCode = () => {
    let tableHtml = '';
    
    // 生成表格部分
    for (let i = 0; i < tableData.rows; i++) {
      tableHtml += '    <tr>\n';
      
      for (let j = 0; j < tableData.cols; j++) {
        const cell = tableData.cells[i][j];
        if (cell.rowSpan === 0 || cell.colSpan === 0) continue;
        
        const attrs = [];
        if (cell.rowSpan > 1) attrs.push(`rowspan="${cell.rowSpan}"`);
        if (cell.colSpan > 1) attrs.push(`colspan="${cell.colSpan}"`);
        
        tableHtml += `      <td ${attrs.join(' ')} style="border: 1px solid #d9d9d9; padding: 8px;">${cell.content || '&nbsp;'}</td>\n`;
      }
      
      tableHtml += '    </tr>\n';
    }
    
    // 完整的HTML文档
    return `<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>表格预览</title>
  <style>
    body {
      font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
      margin: 0;
      padding: 20px;
      display: flex;
      justify-content: center;
    }
    table {
      border-collapse: collapse;
      width: 100%;
      max-width: 800px;
      margin: 0 auto;
      box-shadow: 0 2px 8px rgba(0,0,0,0.1);
    }
    td {
      border: 1px solid #d9d9d9;
      padding: 8px;
      min-height: 20px;
    }
    tr:nth-child(even) {
      background-color: #f9f9f9;
    }
    .title {
      text-align: center;
      margin-bottom: 20px;
      color: #333;
    }
  </style>
</head>
<body>
  <div>
    <h1 class="title">表格预览</h1>
    <table>
      <tbody>
${tableHtml}      </tbody>
    </table>
  </div>
</body>
</html>`;
  };

  // 生成Vue组件
  const generateVueCode = () => {
    let tableRows = '';
    
    for (let i = 0; i < tableData.rows; i++) {
      tableRows += '      <tr>\n';
      
      for (let j = 0; j < tableData.cols; j++) {
        const cell = tableData.cells[i][j];
        if (cell.rowSpan === 0 || cell.colSpan === 0) continue;
        
        const attrs = [];
        if (cell.rowSpan > 1) attrs.push(`:rowspan="${cell.rowSpan}"`);
        if (cell.colSpan > 1) attrs.push(`:colspan="${cell.colSpan}"`);
        
        tableRows += `        <td ${attrs.join(' ')}>${cell.content || '&nbsp;'}</td>\n`;
      }
      
      tableRows += '      </tr>\n';
    }
    
    return `<template>
  <div class="table-container">
    <table>
      <tbody>
${tableRows}      </tbody>
    </table>
  </div>
</template>

<script>
export default {
  name: 'CustomTable'
}
</script>

<style scoped>
.table-container {
  display: flex;
  justify-content: center;
  width: 100%;
}
table {
  border-collapse: collapse;
  width: 100%;
  max-width: 800px;
  margin: 0 auto;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}
td {
  border: 1px solid #d9d9d9;
  padding: 8px;
  min-height: 20px;
}
tr:nth-child(even) {
  background-color: #f9f9f9;
}
</style>`;
  };

  // 生成React组件
  const generateReactCode = () => {
    let tableRows = '';
    
    for (let i = 0; i < tableData.rows; i++) {
      tableRows += '          <tr>\n';
      
      for (let j = 0; j < tableData.cols; j++) {
        const cell = tableData.cells[i][j];
        if (cell.rowSpan === 0 || cell.colSpan === 0) continue;
        
        const attrs = [];
        if (cell.rowSpan > 1) attrs.push(`rowSpan={${cell.rowSpan}}`);
        if (cell.colSpan > 1) attrs.push(`colSpan={${cell.colSpan}}`);
        
        tableRows += `            <td ${attrs.join(' ')}>${cell.content || '\u00A0'}</td>\n`;
      }
      
      tableRows += '          </tr>\n';
    }
    
    return `import React from 'react';
import './CustomTable.css';

const CustomTable = () => {
  return (
    <div className="table-container">
      <table>
        <tbody>
${tableRows}        </tbody>
      </table>
    </div>
  );
};

export default CustomTable;

// CSS文件内容 (CustomTable.css):
/*
.table-container {
  display: flex;
  justify-content: center;
  width: 100%;
}
table {
  border-collapse: collapse;
  width: 100%;
  max-width: 800px;
  margin: 0 auto;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}
td {
  border: 1px solid #d9d9d9;
  padding: 8px;
  min-height: 20px;
}
tr:nth-child(even) {
  background-color: #f9f9f9;
}
*/`;
  };

  // 根据当前选项卡获取代码
  const getCode = () => {
    switch (activeTab) {
      case 'html':
        return generateHTMLCode();
      case 'vue':
        return generateVueCode();
      case 'react':
        return generateReactCode();
      default:
        return '';
    }
  };

  // 复制代码到剪贴板
  const copyCode = () => {
    const code = getCode();
    navigator.clipboard.writeText(code)
      .then(() => {
        setCopySuccess(true);
        message.success('代码已复制到剪贴板');
        setTimeout(() => setCopySuccess(false), 2000);
      })
      .catch(() => {
        message.error('复制失败，请手动复制');
      });
  };
  
  // 下载代码
  const downloadCode = () => {
    const code = getCode();
    const blob = new Blob([code], { type: 'text/plain' });
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    
    const fileExtension = activeTab === 'html' ? 'html' : activeTab === 'vue' ? 'vue' : 'jsx';
    link.download = `table.${fileExtension}`;
    
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    
    message.success(`已下载 table.${fileExtension} 文件`);
  };
  
  // 直接预览表格
  const previewTable = () => {
    if (activeTab !== 'html') {
      message.warning('只能预览HTML格式的表格');
      return;
    }
    
    const htmlCode = generateHTMLCode();
    const blob = new Blob([htmlCode], { type: 'text/html' });
    const url = URL.createObjectURL(blob);
    
    // 在新窗口中打开
    window.open(url, '_blank');
    
    // 延迟释放URL对象
    setTimeout(() => URL.revokeObjectURL(url), 1000);
  };

  return (
    <PreviewContainer>
      <Title level={4} style={{ margin: '0 0 16px 0', textAlign: 'center' }}>代码预览</Title>
      
      <Tabs 
        activeKey={activeTab} 
        onChange={setActiveTab}
        type="card"
        centered
        style={{ backgroundColor: 'white', padding: '8px', borderRadius: '4px' }}
      >
        <TabPane tab="HTML" key="html" />
        <TabPane tab="Vue" key="vue" />
        <TabPane tab="React" key="react" />
      </Tabs>
      
      <CodeBlock>{getCode()}</CodeBlock>
      
      <ButtonContainer>
        <StyledButton 
          type="primary" 
          icon={copySuccess ? <CheckOutlined /> : <CopyOutlined />}
          onClick={copyCode}
        >
          {copySuccess ? '已复制' : '复制代码'}
        </StyledButton>
        
        <StyledButton 
          icon={<DownloadOutlined />}
          onClick={downloadCode}
        >
          下载代码
        </StyledButton>
        
        <StyledButton
          type="primary"
          icon={<EyeOutlined />}
          onClick={previewTable}
          style={{ backgroundColor: activeTab === 'html' ? '#52c41a' : undefined }}
          disabled={activeTab !== 'html'}
        >
          直接预览
        </StyledButton>
      </ButtonContainer>
      
      {activeTab === 'html' && (
        <div style={{ marginTop: '12px', fontSize: '13px', color: '#888' }}>
          提示: 点击"直接预览"可以在新窗口打开表格，或下载HTML文件后直接在浏览器中打开
        </div>
      )}
    </PreviewContainer>
  );
};

export default CodePreview;